- User defined Functions in Xi -
Looking back upon the last example it's suggestive to write a function that computes the factorial of a given integer number. On the one hand Xi supports a C-like function definition style:
( 1)>int fact(int n) { ( 2)> int i, result=1; ( 3)> for (i=1; i<=n; i++) result*=i; ( 4)> return result; ( 5)>} ( 6)>print(fact(4)); <int> 24On the other hand Xi includes a Fortran 90 like list of arguments. This is especially beneficial for complicated numerical functioncalls with many arguments. Some of these arguments will be performed with default values, so at the end the user normally gets a compact functioncall which only needs the most important arguments.
( 7)>int fact2(int n, int pro_results=0) { ( 8)> int i, result=1; ( 9)> for (i=1; i<=n; i++) { ( 10)> result*=i; ( 11)> if (pro_results != 0) printf("%d ",result); ( 12)> } ( 13)> return result; ( 14)>}You can use the function fact2 in the same way as fact,
( 15)>print(fact2(4)); <int> 24Further applicabilities are:
( 16)>print(fact(4,1)); 1 2 6 24 <int> 24 ( 17)>print(fact2(\n=4,\pro_results=1)); 1 2 6 24 <int> 24 ( 18)>print(fact2(\pro_results=1,\n=4)); 1 2 6 24 <int> 24 ( 19)>print(fact2(4,\pro_results)); 1 2 6 24 <int> 24The normal way as shown in line 16 is to write the arguments in the order coded in the function itself. But if you name the arguments (line 17), you can choose the order you prefer (shown in line 18). Using only the name of the argument without a value the interpreter will set the value of this argument to one.
Maybe you have a more complicated combination of arguments with defaults and named arguments in mind. In general the interpreter first sets all named arguments to the given value (or one). Then he fills the remaining arguments with the unnamed values from left to right leaving out the already filled arguments. Hopefully the rest of the arguments will have default values otherwise you will get an error message.
Sometimes it is useful to undefine a functionname to reuse it in another context.
( 20)>delete fact2();Now you indubitably want to save this function for further use. Use your favorite editor for coding and saving. It is important that the file has the extension .xi . You can use such files in your Xi-session with the command
( 21)>#include filename /* filename without the extension .xi */Xi has the following searchconditions: